package com.qianying.gateway.filter;

import com.qianying.comment.AesUtil;
import com.qianying.comment.CommonResult;
import com.qianying.comment.JsonUtil;
import com.qianying.dto.TockenDTO;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

/**
 * 网关认证过滤器，模拟解析 Authorization token，提取用户ID
 */
@Component
public class AuthFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //chain.doFilter(request, response);
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String path = req.getRequestURI();
        if (!path.startsWith("/admin")) {
            chain.doFilter(request, response);
            return;
        }

        String authorization = req.getHeader("Authorization");
        TockenDTO tockenDTO = null;
        if (authorization==null||authorization.trim().isEmpty()){
            authorization="OlGZtITzoR0B/POzblseWWfwWwyG4V7tAnrjNcY6OjM=";
        }

        if (authorization!=null&&!authorization.trim().isEmpty()) {
            try {
                String dotStr = AesUtil.decrypt(authorization);
                tockenDTO = JsonUtil.fromJson(dotStr, TockenDTO.class);
                if (tockenDTO == null) {
                    writeBackStatus(resp, CommonResult.failed("获取tocken对象错误！"));
                    return;
                }
            } catch (RuntimeException e) {
                writeBackStatus(resp, CommonResult.failed("解析json出错！"));
            }

        } else {
            writeBackStatus(resp, CommonResult.failed("没有获取到tocken！"));
            return;
        }

        if (tockenDTO.getRoleId() == null || tockenDTO.getUserID() == null) {
            writeBackStatus(resp, CommonResult.failed("用户数据丢失！"));
            return;
        }

        final TockenDTO finalTockenDTO = tockenDTO;

        req.setAttribute("userId", finalTockenDTO.getUserID());
        req.setAttribute("roleId", finalTockenDTO.getRoleId());
        chain.doFilter(req, response);
    }


    private void writeBackStatus(HttpServletResponse resp, CommonResult<?> result) throws IOException {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.setContentType("application/json;charset=UTF-8");
        resp.getWriter().write(JsonUtil.toJson(result));
    }
}
